'use strict'
//引入express框架
var express = require('express');
//引入http
var http = require('http');
//引入文件管理的fs
var fs = require('fs');
//引入路径
var path = require('path');
//引入静态文件内容插件
var serveIndex = require('serve-index');
//初始化 express框架;
let app = express();
//express挂载
app.use(express.static('./public'));

//引入scoket
var { ioinit, logger, USERCOUNT } = require('./scoket');

app.use('/index', function (req, res, next) {

  logger.debug('主页面请求')
  console.log('主页面请求', req.url, req.url.indexOf('/favicon.ico') != -1);
  if (req.url.indexOf('/index') != -1) { }
  if (req.url.indexOf('/tall') != -1) {
    console.log('进到消息通话页面');
    res.sendFile(path.resolve(__dirname, './static/tall.html'));
  } else if (req.url.indexOf('/webrtc') != -1) {
    console.log('进到视频通话页面123');
    res.sendFile(path.resolve(__dirname, './view/index.html'))
  } else if (req.url.indexOf('/js') != -1) {
    res.sendFile(path.resolve(__dirname, './static/client.js'));
  } else if (req.url.indexOf('/tjs') != -1) {
    res.sendFile(path.resolve(__dirname, './view/tjs/client.js'));
  } else {
    res.send({ code: 400, message: '请求的页面不见了', success: false })
  }
});
//挂载静态文件夹下所有文件名称路径
app.use('/filepath', serveIndex('./public'));
app.use('/', (req, res, next) => {
  console.log('荣阔所有路径', req.url);
  res.sendFile(path.resolve(__dirname, './static/favicon.ico'));
})

let serve = http.createServer(app)
let io = ioinit(serve)
serve.listen(3100)

io.sockets.on('connection', (socket) => {
  console.log('创建socket', 11);
  logger.info("connection");

  //转发信息
  socket.on('message', (room, data) => {
    console.log('message消息推送', 33,room,data);
    logger.info("message data " + socket.id + " " + room, data);
    socket.emit('message', room, socket.id, '回复链接')//房间内所有人,除自己外
  });

  //用户加入
  socket.on('join', (room) => {
    console.log('用户加入', room, 22);
    logger.info("join", ",room = ", room, ",socket.id = ", socket.id);

    
    var myRoom = io.sockets.adapter.rooms[room];
    console.log('===========', myRoom);
    var users = (myRoom) ? Object.keys(myRoom.sockets).length : 0;
    logger.debug('the number of user in room is:' + users)

    //处理一对一通信
    if (users < USERCOUNT) {
      //给本人回信息
      socket.emit('joined', room, socket.id);
      if (users > 1) {
        socket.to(room).emit('otherjoin', room, socket.id);
      }
    } else {
      socket.leave(room);
      socket.emit('full', room, socket.id);
    }
  });

  //用户离开
  socket.on('leave', (room) => {
    console.log('用户离开', 44);
    var myRoom = io.sockets.adapter.rooms[room];
    var users = (myRoom) ? Object.keys(myRoom.sockets).length : 0;
    //users-1
    logger.debug('the number of user in room is:' + (users - 1));

    socket.to(room).emit('exit', room, socket.id);
    socket.emit('leaved', room, socket.id);

  });
});

serve.on('error', (error) => {
  console.log('启动失败', error)
})
serve.on('listening', () => {
  logger.debug('监听3100端口启动-启动成功')
  console.log('3100端口启动成功');
})
